<template>
  <div>
    <el-card>
      <el-form ref="paperFormRef" :model="paperForm" :rules="paperFormRules" label-width="90px">
        <el-form-item label="论文引用" prop="reference">
          <el-input v-model="paperForm.reference" placeholder="请输入 APA 格式引用" v-on:change="readRef()"></el-input>
        </el-form-item>
        <el-form-item label="论文 DOI" prop="doi">
          <el-input v-model="paperForm.doi" placeholder="请输入数字对象唯一标识符" ></el-input>
        </el-form-item>
        <el-form-item label="论文名称" prop="name">
          <el-input v-model="paperForm.name" placeholder="请输入论文名称" ></el-input>
        </el-form-item>
        <el-form-item label="作者姓名" prop="author">
          <el-input v-model="paperForm.author" placeholder="!为了有较好的显示效果，请只输入第一(二)作者"></el-input>
        </el-form-item>
        <el-form-item label="会议(期刊)" prop="inst">
          <el-input v-model="paperForm.inst" placeholder="请输入会议(期刊)名称 !请按会议/期刊缩写+年份缩写命名 例如 HPCC18、TPEL20"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="paperForm.type">
            <el-radio label="c">会议论文</el-radio>
            <el-radio label="j">期刊论文</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出版时间" prop="pubDate">
          <el-col :span="11">
            <el-date-picker type="month" placeholder="选择日期" v-model="paperForm.pubDate" format="yyyy 年 MM 月" style="width: 100%;"></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="上传材料">
          <el-upload
              :limit="1"
              ref="uploadRef"
              drag
              :file-list="fileList"
              :data="paperForm"
              :on-change="uploadChanged"
              :before-remove="uploadChanged"
              :on-exceed="uploadExceed"
              :on-success="uploadSucceed"
              :before-upload="beforeFileUpload"
              :action="baseURI+'upload'"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <el-alert
              style="width: 725px"
              title="只能上传 ppt/pptx 文件, 且文件大小不超过 10Mb"
              type="warning">
          </el-alert>
        </el-form-item>
        <el-form-item>
          <el-button v-if="isAdd" type="primary" @click="submitPaper" :disabled="uploading">立即创建</el-button>
          <el-button v-else type="primary" @click="submitPaper" :disabled="uploading">立即更新</el-button>
          <el-button v-if="isAdd" type="info" @click="resetPaper">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  props: {
    isAdd: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    activeTab () {
      return this.$store.state.activeTab
    }
  },
  watch: {
    activeTab: function (val, oldval) {
      if (this.isAdd) return
      if (val === 'updatePaper') {
        if (!this.$store.state.activePaper) {
          this.$store.commit('setActiveTab', 'viewPaper')
          this.$notify({ title: '注意', message: '请先选择要更新的论文', type: 'warning' })
          return
        }
        var form = this.$store.state.activePaper
        form = JSON.parse(JSON.stringify(form))
        form.pubDate = new Date(form.pubDate)
        delete form.addTime
        this.paperForm = form
        if (form.filename) this.fileList = [{ name: form.filename, uploadId: form.uploadId }]
      } else {
        this.$refs.paperFormRef.resetFields()
        this.$refs.uploadRef.clearFiles()
        this.$store.commit('setActivePaper', null)
      }
    }
  },
  data () {
    return {
      baseURI: null,
      uploading: false,
      fileList: [],
      paperForm: {
        token: null,
        reference: null,
        doi: null,
        name: null,
        author: null,
        inst: null,
        type: null,
        pubDate: null,
        uploadId: null
      },
      paperFormRules: {
        doi: [
          { required: true, message: '请输入数字对象唯一标识符(DOI)', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入论文名称', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者姓名', trigger: 'blur' }
        ],
        inst: [
          { required: true, message: '请输入会议（期刊）名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择论文类型', trigger: 'blur' }
        ],
        pubDate: [
          { required: true, message: '请选择出版时间', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.baseURI = this.$http.defaults.baseURL
  },
  methods: {
    submitPaper () {
      this.paperForm.token = window.sessionStorage.getItem('token')
      this.$refs.paperFormRef.validate(async valid => {
        if (!valid) return
        if (this.fileList.length > 0) this.paperForm.uploadId = this.fileList[0].uploadId
        else this.paperForm.uploadId = null
        const { data: res } = await this.$http.post('paper/submit', this.paperForm)
        if (!res.success) {
          this.$message.error(res.info)
        } else {
          this.$message.success(res.info)
          this.$store.commit('setPaperListBlur', true)
          if (this.isAdd) this.resetPaper()
          else this.$store.commit('setActiveTab', 'viewPaper')
        }
      })
    },
    resetPaper () {
      this.uploading = false
      this.paperForm.uploadId = null // 此元素没有绑定，需要单独清理
      this.fileList = []
      this.$refs.uploadRef.abort()
      this.$refs.paperFormRef.resetFields()
      this.$refs.uploadRef.clearFiles()
    },
    beforeFileUpload (file) {
      const isPPT = file.type === 'application/vnd.ms-powerpoint'
      const isPPTX = file.type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isPPT && !isPPTX) this.$message.error('上传文件只能是 PPT 格式!')
      if (!isLt10M) this.$message.error('上传文件大小不能超过 10MB!')
      this.uploading = (isPPT || isPPTX) && isLt10M
      this.paperForm.token = window.sessionStorage.getItem('token')
      return this.uploading
    },
    uploadChanged (file, fileList) {
      this.fileList = fileList
    },
    uploadExceed (file, fileList) {
      this.$message.error('只能上传单个文件')
    },
    uploadSucceed (res, file, fileList) {
      this.uploading = false
      if (!res.success) {
        this.$message.error(res.info)
      }
      this.fileList[0].uploadId = res.id
    },
    readRef () {
      const ref = this.paperForm.reference
      if (!this.paperForm.author) {
        var str = ref.replace('and', ',')
        var index = str.indexOf(', ')
        var index2 = str.indexOf(', "')
        if (index2 > 16) index2 = str.indexOf(', ', index + 1)
        this.paperForm.author = str.substr(0, index2)
      }
      if (!this.paperForm.doi) {
        index = ref.indexOf('doi: ')
        if (index > -1) this.paperForm.doi = ref.substr(index + 5, ref.length - index - 6)
      }
      if (!this.paperForm.name) {
        index = ref.indexOf('"')
        index2 = ref.indexOf(',"')
        this.paperForm.name = ref.substr(index + 1, index2 - index - 1)
      }
    }
  }
}
</script>

<style scoped>
</style>
